package co.yixiang.modules.activity.rest;

import cn.hutool.core.util.StrUtil;
import co.yixiang.aop.log.Log;
import co.yixiang.exception.BadRequestException;
import co.yixiang.modules.activity.domain.YxStoreCoupon;
import co.yixiang.modules.activity.domain.YxStoreCouponProduct;
import co.yixiang.modules.activity.service.YxStoreCouponProductService;
import co.yixiang.modules.activity.service.YxStoreCouponService;
import co.yixiang.modules.activity.service.dto.YxStoreCouponDTO;
import co.yixiang.modules.activity.service.dto.YxStoreCouponProductDto;
import co.yixiang.modules.activity.service.dto.YxStoreCouponQueryCriteria;
import co.yixiang.utils.OrderUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
* @author hupeng
* @date 2019-11-09
*/
@Api(tags = "优惠券管理")
@RestController
@RequestMapping("api")
public class YxStoreCouponController {

    @Autowired
    private YxStoreCouponService yxStoreCouponService;
    @Autowired
    private YxStoreCouponProductService couponProductService;

    @Log("查询")
    @ApiOperation(value = "查询")
    @GetMapping(value = "/yxStoreCoupon")
    @PreAuthorize("@el.check('admin','YXSTORECOUPON_ALL','YXSTORECOUPON_SELECT')")
    public ResponseEntity getYxStoreCoupons(YxStoreCouponQueryCriteria criteria, Pageable pageable){
        return new ResponseEntity(yxStoreCouponService.queryAll(criteria,pageable),HttpStatus.OK);
    }

    @Log("新增")
    @ApiOperation(value = "新增")
    @PostMapping(value = "/yxStoreCoupon")
    @PreAuthorize("@el.check('admin','YXSTORECOUPON_ALL','YXSTORECOUPON_CREATE')")
    public ResponseEntity create(@RequestBody JSONObject params){
        JSONObject result = new JSONObject();

        YxStoreCoupon resources = params.toJavaObject(YxStoreCoupon.class);
        JSONArray goodsList = params.getJSONArray("goodsList");
        int size = goodsList.size();
        StringBuilder ids = new StringBuilder();
        if(resources.getType() == 2 || resources.getType() == 3){
            Assert.isTrue(goodsList!= null && size > 0,"对应商品不能为空");
            for (int i = 0; i < size; i++) {
                JSONObject goods = goodsList.getJSONObject(i);
                Integer id = goods.getInteger("id");
                if((i+1) == size)  ids.append(id);
                else ids.append(id).append(",");
            }
        }
        Long addTime = System.currentTimeMillis()/1000L;
        resources.setAddTime(addTime.intValue());
        resources.setIsDel(0);
        resources.setAddTime(OrderUtil.getSecondTimestampTwo());
        resources.setProductIds(ids.toString());

        YxStoreCouponDTO coupon = yxStoreCouponService.create(resources);
        result.put("coupon",coupon);
        result.put("productList",null);
        if((coupon.getType() == 2 || coupon.getType() == 3) && goodsList != null && size > 0){
            Integer cid = coupon.getId();
            List<YxStoreCouponProduct> productList = new ArrayList<>(size);
            for (int i = 0; i < size; i++) {
                JSONObject goods = goodsList.getJSONObject(i);
                YxStoreCouponProduct product = new YxStoreCouponProduct();
                product.setCid(cid);
                product.setAddTime(addTime.intValue());
                product.setProductId(goods.getInteger("id"));
                product.setIsDel(0);
                productList.add(product);
            }
            List<YxStoreCouponProductDto> list = couponProductService.createList(productList);
            result.put("productList",list);
        }
        return new ResponseEntity(result,HttpStatus.CREATED);
    }

    @Log("修改")
    @ApiOperation(value = "修改")
    @PutMapping(value = "/yxStoreCoupon")
    @PreAuthorize("@el.check('admin','YXSTORECOUPON_ALL','YXSTORECOUPON_EDIT')")
    public ResponseEntity update(@Validated @RequestBody YxStoreCoupon resources){
        yxStoreCouponService.update(resources);
        return new ResponseEntity(HttpStatus.NO_CONTENT);
    }

    @Log("删除")
    @ApiOperation(value = "删除")
    @DeleteMapping(value = "/yxStoreCoupon/{id}")
    @PreAuthorize("@el.check('admin','YXSTORECOUPON_ALL','YXSTORECOUPON_DELETE')")
    public ResponseEntity delete(@PathVariable Integer id){
        //if(StrUtil.isNotEmpty("22")) throw new BadRequestException("演示环境禁止操作");
        YxStoreCoupon resources = new YxStoreCoupon();
        resources.setId(id);
        resources.setIsDel(1);
        yxStoreCouponService.update(resources);
        return new ResponseEntity(HttpStatus.OK);
    }
}